package org.study.bookmanagerclientbyswing.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.util.Map;

public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
    /**
     * 将 Java 对象转换为 Map
     * @param object Java 对象
     * @return Map 表示的对象数据

     */
    public static Map<String, Object> objToMap(Object object) {
        return objectMapper.convertValue(object, Map.class);
    }

    /**
     * 将 Map 转换为 JSON 字符串
     * @param map Map
     * @return JSON 字符串
     */
    public static String mapToJson(Map<String, Object> map) {
        try {
            return objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }//对于错误处理，可以try直接捕捉，而不用throw向上抛
    }
}
